package controller;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import service.UserService;
import utils.LayData;
import utils.Page;

import java.util.List;

@Controller
@RequestMapping("/asyncuser")
public class AsyncUserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/tolist")
    public String toList(){
        return "asyncuser/list";
    }
    @RequestMapping("/list")
    @ResponseBody
    public String list(User user, @RequestParam(value="page",defaultValue = "1")Integer currentPage,
                       @RequestParam(value = "limit",defaultValue = "10")Integer pageSize){
        int totalCount = userService.count(user);
        //计算偏移量
        Integer offset = (currentPage-1)*pageSize;
        List<User> users = userService.findAll(user, offset, pageSize);
        // 构建返回的数据结构
        LayData layData = new LayData(0, "查询成功", totalCount, users);
        return JSON.toJSONString(layData);
    }
    @RequestMapping("/toadd")
    public String toAdd(){
        return "asyncuser/add";
    }
    @RequestMapping("/addSave")
    @ResponseBody
    public String add(User user){
        int result = userService.addUser(user);
        if(result>0){
            return JSON.toJSONString(new LayData(0, "添加成功"));
        }else {
            return JSON.toJSONString(new LayData(500, "添加失败"));
        }
    }
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam("ids") List<Integer> ids){
        int result = userService.deleteUserById(ids);
        if(result>0){
            return JSON.toJSONString(new LayData(0, "删除成功"));
        }else {
            return JSON.toJSONString(new LayData(500, "删除失败"));
        }
    }
    @RequestMapping ("/toupdate")
    public String toupdate(@RequestParam("id") Integer id, Model model){
        // 根据 id 从数据库中获取用户数据
        User user = userService.findUserById(id);
        // 将用户数据添加到模型中
        model.addAttribute("user", user);
        return "asyncuser/update";
    }
    @RequestMapping("/updateSave")
    @ResponseBody
    public String update(User user){
        int result = userService.updateUser(user);
        if(result>0){
            return JSON.toJSONString(new LayData(0, "更新成功"));
        }else {
            return JSON.toJSONString(new LayData(500, "更新失败"));
        }
    }
}







